package x.ovo.wechat.bot;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import x.ovo.wechat.bot.common.entity.event.MessageEvent;
import x.ovo.wechat.bot.common.entity.message.TextMessage;
import x.ovo.wechat.bot.common.event.Event;
import x.ovo.wechat.bot.common.event.EventListener;
import x.ovo.wechat.bot.common.plugin.Plugin;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.Random;

@Slf4j
public class KfcListener extends EventListener<MessageEvent<TextMessage>> {


    private static final Random RANDOM = new Random();
    private JSONArray docs;

    public KfcListener(Plugin plugin) {
        try {
            File file = FileUtil.file(plugin.getDataFolder(), "docs.json");
            this.docs = JSONUtil.readJSONArray(file, StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.error("读取文档失败", e);
            try {
                File file = FileUtil.file("docs.json");
                this.docs = JSONUtil.readJSONArray(file, StandardCharsets.UTF_8);
            } catch (Exception ee) {
                log.error("读取文档失败", ee);
            }
        }
    }

    @Override
    public boolean support(Event<?> event) {
        return event instanceof MessageEvent && event.getSource() instanceof TextMessage && Objects.nonNull(this.docs);
    }

    @Override
    public void onEvent(MessageEvent<TextMessage> event) {
        TextMessage message = event.getSource();
        String userName = message.getFromUser().getUserName();
        String content = event.getContent().toLowerCase();
        if (content.contains("kfc") || content.contains("肯德基") || content.contains("v我50") || content.contains("疯狂星期四")) {
            try {
                OkHttpClient client = (OkHttpClient) this.context.getHttpEngine().getRawEngine();
                Request request = new Request.Builder().url("https://kfc-crazy-thursday.vercel.app/api/index").build();
                Response response = client.newCall(request).execute();
                this.context.getApi().sendText(userName, Objects.requireNonNull(response.body()).string());
            } catch (Exception e) {
                this.context.getApi().sendText(userName, docs.getStr(RANDOM.nextInt(docs.size())));
            }
        }
    }

}
